package fr.znight.chacunsatv.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;

public class SystemManager {

	public static String getForegroundPackageName(Context context)
	{
		ComponentName localComponentName = getTopComponent(context);
		if (localComponentName == null)
			return "";
		return localComponentName.getPackageName();
	}

	public static ComponentName getTopComponent(Context context)
	{
		try
		{
			ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			return ((ActivityManager.RunningTaskInfo)activityManager.getRunningTasks(1).get(0)).topActivity;
		} 
		catch (Exception e) 
		{ 
			return null;
		}
	}

	public static String getAppName(Context context, String packageName)
	{
		final PackageManager pm = context.getPackageManager();
		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities(mainIntent, 0);
		for (ResolveInfo resolveInfo : pkgAppsList) 
		{
			String appName;
			ApplicationInfo appInfo = resolveInfo.activityInfo.applicationInfo;
			try {
				PackageInfo pi = pm.getPackageInfo(appInfo.packageName, 0);
				appName = (String) pm.getApplicationLabel(appInfo);
				if (appInfo.packageName.equals(packageName))
					return appName;

			} 
			catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		} 

		return "";
	}

	public static Drawable getAppDrawable(Context context, String packageName)
	{
		final PackageManager pm = context.getPackageManager();
		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities(mainIntent, 0);
		for (ResolveInfo resolveInfo : pkgAppsList) 
		{
			Drawable drawable;
			ApplicationInfo appInfo = resolveInfo.activityInfo.applicationInfo;
			try {
				PackageInfo pi = pm.getPackageInfo(appInfo.packageName, 0);
				drawable = pm.getApplicationIcon(appInfo);
				if (appInfo.packageName.equals(packageName))
					return drawable;

			} 
			catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		} 

		return null;
	}

	public static ArrayList<AppObject> getAppObjectList(Context context)
	{
		//
		//On r�cup�re la liste des applications
		//

		ArrayList<AppObject> list = new ArrayList<AppObject>();

		final PackageManager pm = context.getPackageManager();
		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities(mainIntent, 0);
		for (ResolveInfo resolveInfo : pkgAppsList) 
		{
			ApplicationInfo appInfo = resolveInfo.activityInfo.applicationInfo;
			AppObject app = new AppObject();
			app.setPackageName(appInfo.packageName);
			try {
				PackageInfo pi = pm.getPackageInfo(appInfo.packageName, 0);
				app.setAppName((String) pm.getApplicationLabel(appInfo));
				app.setIcon(pm.getApplicationIcon(appInfo));
				if (!app.getPackageName().equals(context.getPackageName()) && !list.contains(app))
					list.add(app);
			} 
			catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		} 

		Collections.sort(list, AppObject.AppObjectComparator);
		return list;
	}

	public static void addToFavorite(final Context context)
	{
		String packageName = getForegroundPackageName(context);

		if (PrefsHelper.containsKey(context, PrefsHelper.FAV_APP_COUNT))
		{
			for (int i = 1; i < PrefsHelper.getInt(context, PrefsHelper.FAV_APP_COUNT); i++)
			{
				if (PrefsHelper.getString(context, PrefsHelper.FAV_APP_KEY_PREFIX + i).equals(packageName))
					return;
			}

			PrefsHelper.setInt(context, PrefsHelper.FAV_APP_COUNT, PrefsHelper.getInt(context, PrefsHelper.FAV_APP_COUNT) + 1);
		}
		else
		{
			PrefsHelper.setInt(context, PrefsHelper.FAV_APP_COUNT, 1);
			PrefsHelper.setString(context, PrefsHelper.FAV_APP_KEY_PREFIX + "1", packageName);
		}
	}

	public static void changeChaine(Context context, String channelUri)
	{
		// Creates a new Intent object with the ACTION_VIEW action
		Intent mViewIntent = new Intent(Intent.ACTION_VIEW);

		// This code assumes that the channel URI is now in mUri
		// Sets the channel Uri as the data for the Intent
		mViewIntent.setData(Uri.parse(channelUri));

		/*
		 * Starts an Activity that can handle ACTION_VIEW and
		 * understands channel URIs. Live TV Player is the default
		 * app for this.
		 */
		context.startActivity(mViewIntent);
	}

	public static HashMap<Integer, ChaineObject> getChaines(Context context)
	{
		HashMap<Integer, ChaineObject> map = new HashMap<Integer, ChaineObject>();

		/*
		 * creates a content URI that points to the channel listing content provider, and
		 * within it the channel listing table.
		 */
		Uri mProviderUri = Uri.parse("content://" + "com.google.android.tv.provider" + "/" + "channel_listing");

		// Defines a string array containing the columns to retrieve (the projection)
		String[] mProjection = {"channel_uri", "channel_name", "channel_number"};

		/*
		 * Makes the query
		 */

		Cursor cur = context.getContentResolver().query(mProviderUri,       // the content URI of the provider
				mProjection,                		// the columns to return
				null,                     	// the column to match against
				null,                  		// the matching value
				"channel_number" + " ASC"   // the sort order
				);

		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			map.put(Integer.parseInt(cur.getString(cur.getColumnIndex("channel_number"))), (new ChaineObject(cur.getString(cur.getColumnIndex("channel_uri")),cur.getString(cur.getColumnIndex("channel_name")),cur.getString(cur.getColumnIndex("channel_number")))));
			cur.moveToNext();
		}
		cur.close();

		return map;
	}
	
	public static ArrayList<ChaineObject> getChannelArray(Context context){
		ArrayList<ChaineObject> listChannel = new ArrayList<ChaineObject>();

		String TAG = new String("DEBUG_CHANNEL_LISTING");
		
		/*
		 * creates a content URI that points to the channel listing content provider, and
		 * within it the channel listing table.
		 */
		Uri mProviderUri = Uri.parse("content://" + "com.google.android.tv.provider" + "/" + "channel_listing");

		// Defines a string array containing the columns to retrieve (the projection)
		String[] mProjection = {"channel_uri", "channel_name", "channel_number"};

		/*
		 * Makes the query
		 */

		Cursor cur = context.getContentResolver().query(mProviderUri,       // the content URI of the provider
				mProjection,                		// the columns to return
				null,                     	// the column to match against
				null,                  		// the matching value
				"channel_number" + " ASC"   // the sort order
				);

		if(cur == null)
			Log.w(TAG, "cursor null");
		if(cur.getCount() == 0)
			Log.w(TAG, "empty cursor");		
		
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			Log.w("DEBUG_SYS", cur.getString(cur.getColumnIndex("channel_name")));

			listChannel.add(new ChaineObject(cur.getString(cur.getColumnIndex("channel_uri")),cur.getString(cur.getColumnIndex("channel_name")),cur.getString(cur.getColumnIndex("channel_number"))));
			cur.moveToNext();
		}
		cur.close();		
		
		for(ChaineObject m:listChannel){
			Log.w("DEBUG_SYS", m.getName());
		}
		
		return listChannel;
	}
	
}
